/**
 * com.cnhis.his.customer.service.SysusersService.java
 */
package com.mbmed.doctor.login.service;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.mbmed.doctor.commons.mapper.ModelVo;
import com.mbmed.doctor.commons.utils.Md5;
import com.mbmed.doctor.commons.utils.StaticKeys;
import com.mbmed.doctor.login.bo.Bck1Bo;
import com.mbmed.doctor.login.bo.SysusersBo;
import com.mbmed.doctor.login.bo.Vae1Bo;
import com.mbmed.doctor.login.mapper.Bck1;
import com.mbmed.doctor.login.mapper.Sysusers;


/**
 * @file  SysusersService.java
 * @author 刘武
 * @version 0.1
 * @todo	Sysusers服务操作接口
 * Copyright(C), 2013-2014
 *		 Shenzhen Coordinates Software Development Co., Ltd.
 * History
 *   	1. Date: 2014-09-26 03:39:55
 *      	Author: 刘武
 *      	Modification: this file was created
 *   	2. ...
 */
@Path("/sysusers")
@Component
public class SysusersService {
	
	private static Logger logger = Logger.getLogger(Sysusers.class);
	
	@Autowired
	private SysusersBo sysusersBo;
	
	@Autowired
	private Bck1Bo bck1Bo;
	
	@Autowired
	private Vae1Bo vae1Bo;
	
	@Context
	Request request;
	
	private String msg;//提示信息

	
	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	/**
	 * 查找所有数据库记录
     * @return type : List 返回查询操作所有符合条件的记录的VO对象集合，操作失败返回null
     */
	@GET
	@Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
    public List<Sysusers> getAll() throws Exception{
        List<Sysusers> list = new ArrayList<Sysusers>();
        return sysusersBo.getAll();        
    }
	
    /**
     * 查找符合条件的所有数据库记录
     * @param id 与数据库中主键对应的值
     * @return type :  返回查询操作所有符合条件的记录的VO对象，操作失败返回null
     * @throws Exception
     */
	@GET
	@Path("{id}")
	@Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
    public Sysusers getSysusers(@PathParam("id") String id) throws Exception{
    	Sysusers sysusers = null;
    	return sysusersBo.get(id);        
    }
	 /**
     * 通过用户名、密码查询用户登录信息
     * @param id 与数据库中主键对应的值
     * @return type :  返回查询操作所有符合条件的记录的VO对象，操作失败返回null
     * @throws Exception
     */
	@POST
	@Path("/login")
	@Produces({MediaType.APPLICATION_JSON})
    public Object getSysusersForLogin(@FormParam("code") String code,
    		@FormParam("loginHost") String loginHost,
//    		@Context HttpServletRequest servletRequest
    		@Context HttpServletResponse servletResponse
    		) throws Exception{
    	
		Sysusers sysusers=null;
		msg = null;
		Map<String,String> paramMap =new HashMap<String,String>();
    	sysusers=sysusersBo.getByCode(code);  
    	
//    	加密狗验证 暂未做
//    	网络访问出错 暂未做
//      判断账号是否已经登录 暂时未用
    	
    	
    	if(sysusers==null){
    		msg="用户名不存在";
    	}
    	else if(1==sysusers.getAuthorized()){
    		msg="该账号被禁用";
    	}else if(new Date().after(sysusers.getExpiryDate())){
    		msg="该账号已过期";
    	}else if(1!=sysusers.getBce41()){
    		msg="该员工不在职";
    	}else if(!"01".equals(sysusers.getAaa01())){
    		msg="该员工员工没有医生工作站权限";
    	}
    	
    	//修改用户登陆状态，机器名称
    	if(msg==null){
    		Map<String,Object> loginSateMap = new HashMap<String,Object>();
    		loginSateMap.put("loginHost", loginHost);
    		loginSateMap.put("loginState", 1);
    		loginSateMap.put("code",code);
    		sysusersBo.save(loginSateMap);
    		sysusers.setResult("SUCCESS");
    		List<Bck1> bck1List= new ArrayList<Bck1>();
    		bck1List = bck1Bo.getByBce01(sysusers.getEmployeeId());
    		sysusers.setBck1List(bck1List);
    	}else{
    		sysusers=new Sysusers();
    		sysusers.setResult(msg);
//        	System.out.println("sadfasf");
    	}
		return sysusers;
	}
	
	
	
	
	 /**
     * 通过用户名、密码验证
     * @param id 与数据库中主键对应的值
     * @return type :  返回查询操作所有符合条件的记录的VO对象，操作失败返回null
     * @throws Exception
     */
	@POST
	@Path("/comparepass")
	@Produces({MediaType.APPLICATION_JSON})
    public ModelVo comparePass(@FormParam("code") String code,
    		@FormParam("pass") String pass
    		) throws Exception{
		
		ModelVo mo = new ModelVo();
    	
		Md5 md5 = new Md5();
        md5.setALGO("AES");
        md5.setKeyValue("4E7FF1C1F04F4B36".getBytes());
		String originalPassword = md5.encrypt(pass); // 解密数据加密密码
		boolean isCheck = sysusersBo.checkSysUser(code, originalPassword);
		if(!isCheck){
			mo.setResultMsg("账号或密码错误！！！");
			mo.setResult(StaticKeys.OH_FALSE);
        	return mo;
		}
		mo.setResult(StaticKeys.OH_SUCCESS);
		return mo;
	}
	
	/**
     * 上传日志文件
     * @throws Exception
     */
	@POST
	@Path("/uploadLog")
	@Produces({MediaType.APPLICATION_JSON})
    public void uploadLog(
    		@Context HttpServletRequest request,
    		@Context HttpServletResponse response
    		) throws Exception{
    	
		ServletInputStream in = request.getInputStream();
		byte[] buffer = new byte[1024];
		File file = new File(request.getSession().getServletContext().getRealPath("/mobile/log/"));
		if (!file.exists()) {
			file.mkdirs();
		}
		File logFile = new File(file, "error.log");
		
		FileOutputStream out = new FileOutputStream(logFile);
		int len = in.read(buffer, 0, 1024);
		while( len!=-1){
			out.write(buffer,0,len);
			len = in.read(buffer, 0, 1024);
		}
		out.close();
		in.close();
	}
	
	
	@GET
	@Path("/GetVersion")
	@Produces(MediaType.APPLICATION_JSON)
	public String GetVersion() throws Exception {
		return sysusersBo.GetVersion();
	}
	
	@POST
	@Path("/updateVersion")
	@Produces(MediaType.APPLICATION_JSON)
	public String updateVersion(@FormParam("version1") java.lang.String version1,
			@Context HttpServletResponse re) throws Exception {
		return sysusersBo.updateVersion(version1);
	}
	
	/**
     * 确认账号密码
     * @param id 与数据库中主键对应的值
     * @return type :  返回查询操作所有符合条件的记录的VO对象，操作失败返回null
     * @throws Exception
     */
	@GET
	@Path("/confirmpasswd")
	@Produces({MediaType.APPLICATION_JSON})
    public ModelVo confirmPasswd(@QueryParam("name") java.lang.String name,
    		@QueryParam("pwd") java.lang.String pwd
    		) throws Exception{
		ModelVo modelVo = new ModelVo();
		Sysusers user = new Sysusers();
//    	return vae1Bo.get(id); 
		user = sysusersBo.getCode(name);
		String workPass = user.getWorkPass();
		if(pwd.equals(workPass)){
			modelVo.setResult("SUCCESS");
		}else{
			modelVo.setResult("FALSE");
		}
		
		modelVo.setResult("SUCCESS");
		
    	return modelVo;
    }
   
	
    	
    /**
     * 向数据库中插入一条记录
     * @param vo 与数据库中记录对应的值对象
     * @return type : 返回插入操作是否成功
     * @throws Exception
     */
	@POST
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Sysusers saveSysusers(
			@FormParam("id") java.lang.Integer id,
			@FormParam("code") java.lang.String code,
			@FormParam("employeeId") java.lang.Integer employeeId,
			@FormParam("name") java.lang.String name,
			@FormParam("fullName") java.lang.String fullName,
			@FormParam("password") java.lang.String password,
			@FormParam("description") java.lang.String description,
			@FormParam("privilege") java.lang.Short privilege,
			@FormParam("authorized") java.lang.Short authorized,
			@FormParam("createDate") java.util.Date createDate,
			@FormParam("expiryDate") java.util.Date expiryDate,
			@FormParam("loginHost") java.lang.String loginHost,
			@FormParam("loginState") java.lang.Byte loginState,
			@FormParam("workPass") java.lang.String workPass,
			@FormParam("checkState") java.lang.Integer checkState,
			@Context HttpServletResponse servletResponse
	) throws Exception {
		Sysusers sysusers = new Sysusers();
		sysusers.setId(id);
		sysusers.setCode(code);
		sysusers.setEmployeeId(employeeId);
		sysusers.setName(name);
		sysusers.setFullName(fullName);
		sysusers.setPassword(password);
		sysusers.setDescription(description);
		sysusers.setPrivilege(privilege);
		sysusers.setAuthorized(authorized);
		sysusers.setCreateDate(createDate);
		sysusers.setExpiryDate(expiryDate);
		sysusers.setLoginHost(loginHost);
		sysusers.setLoginState(loginState);
		sysusers.setWorkPass(workPass);
		sysusers.setCheckState(checkState);

		return sysusers = sysusersBo.save(sysusers);

	}
	/**
     * 删除数据库中与传入的值对象对应的记录
     * @param vo 与数据库中记录对应的值对象
     * @return type : boolean 返回删除操作是否成功
     * @throws Exception
     */
	@DELETE
	@Path("{id}")
	public boolean removeSysusers(@PathParam("id") String id) throws Exception{
		if(id == null) return false;
    	return sysusersBo.remove(id);

	}
	
	
	/**
	 * 获取版本信息 queryMobileVersion
	 * @param MVS07 tinyint  类型0:移动医生站，1：移动护士站，2：移动输液站
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@GET
	@Path("/queryMobileVersion")
	@Produces({MediaType.APPLICATION_JSON})
    public ModelVo queryMobileVersion(@QueryParam("MVS07") Integer MVS07) throws Exception{
		Map paramMap = new HashMap();
		MVS07=MVS07==null?2:MVS07;
		paramMap.put("MVS07", MVS07);
		return sysusersBo.queryMobileVersion(paramMap);
	}
	
}
